<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float: right" type="primary" @click="handleSearchList()" size="small">
          查询搜索
        </el-button>
        <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()" size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="100px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.nickname" class="input-width" placeholder="帐号" clearable></el-input>
          </el-form-item>
          <el-form-item label="系统类别">
            <el-select v-model="listQuery.sysType" placeholder="请选择">
              <el-option label="权限系统" :value="0"></el-option>
              <el-option label="业务系统" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="adminTable" :data="list" style="width: 100%;" v-loading="listLoading" height="500px">
        <el-table-column label=" " type="index" width="50"> </el-table-column>
        <el-table-column label="帐号">
          <template slot-scope="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column label="昵称">
          <template slot-scope="scope">{{ scope.row.nickname }}</template>
        </el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" alt="" style="width: 50px;height: 50px;border-radius: 50%;"
              v-if="scope.row.avatar">
          </template>
        </el-table-column>
        <el-table-column label="电话">
          <template slot-scope="scope">{{ scope.row.phone }}</template>
        </el-table-column>
        <el-table-column label="邮箱" width='150'>
          <template slot-scope="scope">{{ scope.row.email }}</template>
        </el-table-column>
        <el-table-column label="角色" width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{ scope.row.roles ? scope.row.roles.join(', ') : '' }}</template>
        </el-table-column>
        <el-table-column label="系统类别" width="160">
          <template slot-scope="scope">{{ scope.row.sysType == 0 ? '权限系统' : '业务系统' }}</template>
        </el-table-column>
        <el-table-column label="备注" width="160">
          <template slot-scope="scope">{{ scope.row.remarks }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :current-page.sync="listQuery.page" :page-size="listQuery.size"
        :page-sizes="[10, 20, 30, 40]" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="isEdit ? '编辑' : '新增'" :visible.sync="dialogVisible" width="750px">
      <el-form :model="admin" ref="adminForm" label-width="90px" size="small" :rules="rules" label-position="right"
        class="formDiv">
        <el-form-item label="帐号：" prop="username">
          <el-input v-model="admin.username" style="width: 250px" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" v-if="!isEdit">
          <el-input v-model="admin.password" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="昵称：" prop="nickname">
          <el-input v-model="admin.nickname" style="width: 250px" prop="nickname"></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roles">
          <el-select v-model="admin.roles" placeholder="请选择" multiple>
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in allRoleList"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统类别：" prop="sysType">
          <el-select v-model="admin.sysType" placeholder="请选择">
            <el-option label="权限系统" :value="0"></el-option>
            <el-option label="业务系统" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="admin.email" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="电话：">
          <el-input v-model="admin.phone" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="admin.remarks" type="textarea" :rows="5" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="头像：">
          <div v-if="admin.avatar" style="position: relative; width: 178px;
  height: 178px;">
            <img :src="admin.avatar" class="avatar" />
            <i class="el-icon-circle-close"
              style="position: absolute;top: 10px;right: 10px;cursor: pointer;color: red;font-size: 24px;"
              @click="removeImg"></i>
          </div>
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload"
            v-else>
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { deleteAvatar } from "@/api/upload";
import axios from 'axios'
import { addUserInfo, userList, deleteUserInfo, updateUserInfo, roleList } from "@/api/role";

const defaultListQuery = {
  page: 1,
  size: 10,
  nickname: '',
  sysType: '',
};
export default {
  name: "adminList",
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      // 表单数据
      admin: {
        id: "",
        username: "",
        password: "",
        nickname: "",
        email: "",
        phone: "",
        remarks: "",
        roles: [],
        avatar: "",
        sysType: 0
      },
      rules: {
        username: [{ required: true, message: "请输入", trigger: "blur" }],
        password: [{ required: true, message: "请输入", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入", trigger: "blur" }],
        roles: [{ required: true, message: "请选择", trigger: "change" }],
      },
      // 判断是新增还是修改
      isEdit: false,
      allRoleList: [],
    };
  },
  created() {
    this.getList();
    this.getRoleList()
  },
  methods: {
    // 搜索重置
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    // 搜索
    handleSearchList() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 分页数据
    handleSizeChange(val) {
      this.listQuery.page = 1;
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    // 新增用户
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = {
        id: "",
        username: "",
        password: "",
        nickname: "",
        email: "",
        phone: "",
        remarks: "",
        avatar: "",
        roles: [],
        sysType: 0
      };

    },
    // 删除
    handleDelete(index, row) {
      this.$confirm("是否要删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let par = {
          id: row.id,
          avatar: row.avatar
        }
        deleteUserInfo(par).then((response) => {
          if (response.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          }
        });
      });
    },
    // 编辑按钮
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.admin = Object.assign({}, row);
      this.admin.roles = row.roles;
    },
    // 新增修改确认
    handleDialogConfirm() {
      this.$refs.adminForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            let par = {
              id: this.admin.id,
              sysType: this.admin.sysType,
              nickName: this.admin.nickname,
              email: this.admin.email,
              phone: this.admin.phone,
              remarks: this.admin.remarks,
              avatar: this.admin.avatar,
              roles: this.admin.roles,
            }
            updateUserInfo(par).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.dialogVisible = false;
                this.getList()
              }
            })
          } else {
            let par = {
              username: this.admin.username,
              password: this.admin.password,
              sysType: this.admin.sysType,
              nickName: this.admin.nickname,
              email: this.admin.email,
              phone: this.admin.phone,
              remarks: this.admin.remarks,
              avatar: this.admin.avatar,
              roles: this.admin.roles,
            }
            addUserInfo(par).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.dialogVisible = false;
                this.getList()
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 新增修改表格重置
    resetForm() {
      this.$refs.adminForm.resetFields();
      this.dialogVisible = false;
    },
    // 新增修改表格关闭
    closeForm() {
      this.resetForm();
    },
    // 头像上传
    handleAvatarSuccess(res, file) {
      this.admin.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const formData = new FormData(); // 创建FormData对象用于发送表单数据
      formData.append('file', file); // 将文件添加到FormData对象中，键名为'file'（根据后端需求）
      axios.post('http://192.168.10.122:8080/user/addUserAvatar', formData, {
        headers: { 'Content-Type': 'multipart/form-data' } // 设置正确的Content-Type头部信息
      }).then(response => {
        this.admin.avatar = response.data.data;
        console.log('File uploaded successfully:', response); // 上传成功后的处理逻辑
      }).catch(error => {
        console.error('Error uploading file:', error); // 上传失败后的处理逻辑
      });
      return false; // 返回false阻止文件上传
    },
    // 删除头像
    removeImg() {
      let filename = this.admin.avatar.split('/').pop(); // 提取文件名部分
      deleteAvatar({ filename }).then(response => {
        this.admin.avatar = ''; // 清空图片URL
        console.log('File deleted successfully:', response); // 删除成功后的处理逻辑 
      })
    },
    // 获取用户列表
    getList() {
      this.listLoading = true;
      userList(this.listQuery).then((response) => {
        console.log(response, "用户列表");
        if (response.code == 200) {
          this.listLoading = false;
          this.list = response.data.list; //和后端返回的响应数据集合属性要对应
          this.total = response.data.total;
        }
      });
    },
    // 获取角色列表
    getRoleList() {
      roleList().then((response) => {
        console.log(response, "角色列表");

        if (response.code == 200) {
          this.allRoleList = response.data;
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-wrap: wrap;
}

.formDiv {
  .el-form-item {
    width: 50%;

    .el-input--small,
    .el-select--small {
      width: 100% !important;
    }

    /deep/ .el-textarea__inner {
      height: 32px !important;
    }
  }
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

/deep/ .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/deep/ .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
